<%@page contentType="text/html; charset=UTF-8" %>
<%@include file="/WEB-INF/jsp/init.jsp"%>
<script>
    jQuery(function ($) {
        function load() {
            $.ajax({
                url: '/dept/getAllDept',
                success(data) {
                    let html = "";
                    $(data).each(function () {
                        /*html += '<tr>';
                        html += '    <td><input name="id" value="' + this.id + '" type="checkbox"/></td>';
                        html += '    <td>' + (this.no || '') + '</td>';
                        html += '    <td>' + (this.name || '') + '</td>';
                        html += '    <td>' + (this.manager || '') + '</td>';
                        html += '    <td>' + (this.phone || '') + '</td>';
                        html += '    <td>' + (this.description || '') + '</td>';
                        html += '</tr>';*/

                        <%--
                            使用"模板字符串"完成html的拼接
                            特点：
                                1.支持字符串中间换行
                                2.支持${xxx}，其中的内容会被当做js来解析
                         --%>

                        html += `<tr>
                                     <td><input name="id" value="${'${this.id}'}" type="checkbox"/></td>
                                     <td>${"${this.no || ''}"}</td>
                                     <td>${"${this.name || ''}"}</td>
                                     <td>${"${this.manager || ''}"}</td>
                                     <td>${"${this.phone || ''}"}</td>
                                     <td>${"${this.description || ''}"}</td>
                                 </tr>`;
                    });
                    $("#dataBody").html(html);
                }
            });
        }

        load(); // 加载列表

        $("#create-code").blur(function () {
            $("#create-code-err").text("");
            let no = this.value;
            // 格式校验
            if (!/^\d{4}$/.test(no)) {
                $("#create-code-err").text("请输入4位数字！");
            }
            // 唯一性验证：走后端
            $.ajax({
                url: '/dept/checkNo?no='+no,
                success(exists) {
                    if (exists) {
                        $("#create-code-err").text("编号已存在！");
                    }
                }
            });
        });

        $("#saveDeptBtn").click(function () {
            $("#saveDeptForm").ajaxSubmit(function (data) {
                if(data.success) {
                    closeDialog();
                    // 重新加载
                    load();
                    // 重置表单
                    $("#saveDeptForm")[0].reset();
                }
            });
        });

        $("#editBtn").click(function () {
            let $selected = $(":checkbox[name=id]:checked");
            if ($selected.size() != 1) {
                alert("必须且只能选择一个！");
                return;
            }

            /*$.ajax("/dept/getById?id="+$selected.val()).done(function (data) {

                /!*$("#editForm :input[name=no]").val(data.no);
                $("#editForm :input[name=name]").val(data.name);
                $("#editForm :input[name=manager]").val(data.manager);
                $("#editForm :input[name=phone]").val(data.phone);
                $("#editForm :input[name=description]").val(data.description);*!/

                $("#editForm :input[name]").val(function () {
                    return data[this.name];
                });
                $("#editDeptModal").modal('show');
            });*/

            $("#editForm").initForm("/dept/getById?id="+$selected.val());
            $("#editDeptModal").modal('show');
        });

        $("#updateBtn").click(function () {
            $("#editForm").ajaxSubmit(function (data) {
                if(data.success) {
                    closeDialog();
                    // 重新加载
                    load();
                }
            });
        });

        $("#delBtn").click(function () {
            let $selected = $(":checkbox[name=id]:checked");
            if ($selected.size() == 0) {
                alert("请选择要删除的部门！");
                return;
            }

            let ids = $selected.map(function () {
                return this.value;
            }).get().join(",")

            // 查询部门下是否有员工
            $.ajax('/dept/getHasUser?ids='+ids).done(function (data) {
                //if (!(data instanceof Array)) return;
                if (Object.prototype.toString.call(data) != '[object Array]') return;
                if (data.length) {
                    alert("部门【"+data+"】下有用户，无法删除！");
                    return;
                }

                if(!confirm("确定删除吗？")) {
                    return;
                }

                $.ajax({
                    url: '/dept/delete?ids=' + ids,
                    type: 'delete',
                    success(data) {
                        if (data.success) {
                            load();
                        }
                    }
                })
            });
        });
    });
</script>

<!-- 创建部门的模态窗口 -->
<div class="modal fade" id="createDeptModal" role="dialog">
    <div class="modal-dialog" role="document" style="width: 60%;">
        <div class="modal-content">
            <div class="modal-header">
                <button class="close" data-dismiss="modal">
                    <span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title"><span class="glyphicon glyphicon-plus"></span> 新增部门</h4>
            </div>
            <div class="modal-body">
                <form id="saveDeptForm" action="/dept/save" method="post" class="form-horizontal" role="form">
                    <div class="form-group">
                        <label for="create-code" class="col-sm-2 control-label">
                            编号<span style="color:red;">*</span>
                        </label>
                        <div class="col-sm-10">
                            <input name="no" type="text" class="form-control" id="create-code" placeholder="编号为四位数字，不能为空，具有唯一性">
                            <div id="create-code-err" style="color: red;"></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="create-name" class="col-sm-2 control-label">名称&nbsp;</label>
                        <div class="col-sm-10">
                            <input name="name" type="text" class="form-control" id="create-name">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="create-manager" class="col-sm-2 control-label">负责人&nbsp;</label>
                        <div class="col-sm-10">
                            <input name="manager" type="text" class="form-control" id="create-manager">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="create-phone" class="col-sm-2 control-label">电话&nbsp;</label>
                        <div class="col-sm-10">
                            <input name="phone" type="text" class="form-control" id="create-phone">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="create-describe" class="col-sm-2 control-label">描述&nbsp;</label>
                        <div class="col-sm-10">
                            <textarea name="description" class="form-control" rows="3" id="create-describe"></textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">关闭</button>
                <button class="btn btn-primary" id="saveDeptBtn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 修改部门的模态窗口 -->
<div class="modal fade" id="editDeptModal" role="dialog">
    <div class="modal-dialog" role="document" style="width: 60%;">
        <div class="modal-content">
            <div class="modal-header">
                <button class="close" data-dismiss="modal">
                    <span aria-hidden="true">×</span>
                </button>
                <h4 class="modal-title" id="myModalLabel"><span class="glyphicon glyphicon-edit"></span> 编辑部门</h4>
            </div>
            <div class="modal-body">
                <form id="editForm" action="/dept/edit" method="post" class="form-horizontal" role="form">
                    <input type="hidden" name="id" />
                    <div class="form-group">
                        <label for="edit-code" class="col-sm-2 control-label">
                            编号<span style="color:red;">*</span>
                        </label>
                        <div class="col-sm-10">
                            <input name="no" type="text" class="form-control" id="edit-code" placeholder="编号为四位数字，不能为空，具有唯一性" value="1110">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="edit-name" class="col-sm-2 control-label">名称&nbsp;</label>
                        <div class="col-sm-10">
                            <input name="name" type="text" class="form-control" id="edit-name" value="财务部">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="edit-manager" class="col-sm-2 control-label">负责人&nbsp;</label>
                        <div class="col-sm-10">
                            <input name="manager" type="text" class="form-control" id="edit-manager" value="张飞">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="edit-phone" class="col-sm-2 control-label">电话&nbsp;</label>
                        <div class="col-sm-10">
                            <input name="phone" type="text" class="form-control" id="edit-phone" value="010-84846004">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="edit-describe" class="col-sm-2 control-label">描述&nbsp;</label>
                        <div class="col-sm-10">
                            <textarea name="description" class="form-control" rows="3" id="edit-describe">description info</textarea>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button class="btn btn-default" data-dismiss="modal">关闭</button>
                <button class="btn btn-primary" id="updateBtn">更新</button>
            </div>
        </div>
    </div>
</div>

<div class="page-header">
    <h3>部门列表</h3>
</div>
<div class="btn-toolbar" role="toolbar" style="height:50px;">
    <button class="btn btn-primary" data-toggle="modal" data-target="#createDeptModal">
        <span class="glyphicon glyphicon-plus"></span> 创建
    </button>
    <button class="btn btn-default" id="editBtn">
        <span class="glyphicon glyphicon-edit"></span> 编辑
    </button>
    <button class="btn btn-danger" id="delBtn">
        <span class="glyphicon glyphicon-minus"></span> 删除
    </button>
</div>
<div>
    <table class="table table-hover table-striped">
        <thead>
        <tr style="background-color:#d9edf7">
            <th><input id="selectAll" type="checkbox"/></th>
            <th>编号</th>
            <th>名称</th>
            <th>负责人</th>
            <th>电话</th>
            <th>描述</th>
        </tr>
        </thead>
        <tbody id="dataBody"></tbody>
    </table>
</div>